from configparser import ConfigParser
import logging
import sys
import os
import common.helper as helper

conf = ConfigParser()


def read_conf():
    """读取配置文件"""
    logging.debug("读取配置文件...")
    try:
        files = conf.read("./conf.ini", encoding="utf-8")
        if files.__len__() <= 0:
            logging.error("未找到配置文件[conf.ini]")
            sys.exit()
    except:
        logging.error("配置文件[conf.ini]格式有误！")
        sys.exit()


def check_conf():
    """检查配置文件"""

    # 初始化服务唯一标识
    try:
        conf.get("base", "server_id")
    except:
        conf.set("base", "server_id", helper.random_str(10))
        with open("./conf.ini", "w", encoding="utf-8") as f:
            conf.write(f)

    # 资源目录
    try:
        work_folder = conf.get("base", "work_folder")
    except:
        logging.error("未配置[base.work_folder]")
        sys.exit()
    if os.path.exists(work_folder):
        logging.info("音乐资料库目录[work_folder]: " + work_folder)
    else:
        logging.error("work_folder [%s] 不存在" % work_folder)
        sys.exit()

    # 访问密钥
    try:
        conf.get("base", "pass")
    except:
        raise KeyError("未配置[base.pass]")
